package cn.hnu.qq.client.panel;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;

import cn.hnu.qq.client.controller.DefaultModelChartController;
import cn.hnu.qq.client.controller.ListenClientMessageThread;
import cn.hnu.qq.client.controller.ListenServerMessageThread;
import cn.hnu.qq.client.event.MessageEvent;
import cn.hnu.qq.client.listener.MessageListener;
import cn.hnu.qq.entity.ChartContent;
import cn.hnu.qq.entity.TaskEvent;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.ChartMessage;
import cn.hnu.qq.entity.message.DownloadMessage;
import cn.hnu.qq.entity.message.IpInfoMessage;
import cn.hnu.qq.entity.message.Message;
import cn.hnu.qq.frame.DownloadListDialog;
import cn.hnu.qq.frame.SingleChartDialog;
import cn.hnu.qq.global.MessageType;

public class DefaultModelChartPanel extends JPanel implements ActionListener,MessageListener{

	JTextArea readAble;
	JTextArea writeable;
	
	private User ownner;
	
	private DefaultModelChartController controller = DefaultModelChartController.getInstance();
	/**
	 * Create the panel.
	 */
	public DefaultModelChartPanel() {
		setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 10, 528, 267);
		add(scrollPane);
		
		readAble = new JTextArea();
		readAble.setEditable(false);//
		readAble.setLineWrap(true);
		scrollPane.setViewportView(readAble);
		
		readAble.setCaretPosition(readAble.getDocument().getLength());
	
		JPanel panel = new JPanel();
		panel.setBounds(10, 287, 528, 175);
		add(panel);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.NORTH);
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.SOUTH);
		
		JButton sendBtn = new JButton("send");
		panel_2.add(sendBtn);
		sendBtn.addActionListener(this);
		
		JButton btnUploadChartContent = new JButton("upload");
		panel_2.add(btnUploadChartContent);
		btnUploadChartContent.addActionListener(this);
		btnUploadChartContent.setActionCommand("upload");
		JButton btnSaveChartContent = new JButton("save");
		btnSaveChartContent.setActionCommand("save");
		btnSaveChartContent.addActionListener(this);
		panel_2.add(btnSaveChartContent);
		
		JButton btnNewButton = new JButton("download");
		panel_2.add(btnNewButton);
		btnNewButton.setActionCommand("download");
		btnNewButton.addActionListener(this);
		writeable = new JTextArea();
		panel.add(writeable, BorderLayout.CENTER);
	
		this.setSize(554, 472);
		ListenServerMessageThread.getInstance().addMessageListener(this);
		ListenClientMessageThread.getInstance().addMessageListener(this);
	}
	@Override
	protected void paintComponent(Graphics g) {
		Image image = null;
		try {
			image = ImageIO.read(new File("src/main/java/image/03.jpg"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
				
		g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

	}
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("send")){
			if(ownner.getInfo() != null && ownner.getUserClientPort() != null){
				String info = writeable.getText();
				controller.sendChartMessage(ownner,info);
				writeable.setText("");
				info = "【我】" + new SimpleDateFormat("HH-mm-ss").format(new Date())+ "\r\n" + info +"\r\n";
//			readAble.insert(info, readAble.getCaretPosition());
				readAble.append(info);
				readAble.setCaretPosition(readAble.getText().length());  
			}else{
				String info = writeable.getText();
				controller.sendLeaveMessage(ownner,info);
				writeable.setText("");
				info = "【我】" + new SimpleDateFormat("HH-mm-ss").format(new Date())+ "\r\n" + info +"\r\n";
				readAble.append(info);
				readAble.setCaretPosition(readAble.getText().length());  
			}
		}
		if(e.getActionCommand().equals("save")){
			String content = readAble.getText();
			String file = controller.getCurUser().getAcount()+"_"+ownner.getAcount()+"_"+new SimpleDateFormat("yyyy_MM_DD_HH_mm_ss").format(new Date());
			String dir =  "D://chart content";
			File f = new File(dir);
			if(!f.exists()){
				f.mkdir();
			} 
			try {
				DataOutputStream dout = new DataOutputStream(new FileOutputStream(new File(dir+"/"+file)));
				dout.writeUTF(content);
				dout.close();
				JOptionPane.showMessageDialog(this, "记录保存成功！");
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(this, "记录保存出错，请稍后再试");
				e1.printStackTrace();
			}
			return;
		}
		if(e.getActionCommand().equals("upload")){
			controller.sendUploadMessage(ownner,readAble.getText());
		}
		if(e.getActionCommand().equals("download")){
			controller.download(ownner);
		}
	}
	
	
	
	public User getOwnner() {
		return ownner;
	}
	public void setOwnner(User ownner) {
		this.ownner = ownner;
	}

	public void insertMessage(ChartMessage cm){
		String info = cm.getMes();
		info = "【" + cm.getAccount() +"】" + new SimpleDateFormat("HH-mm-ss").format(new Date())+ "\r\n" + info +"\r\n"; 
		readAble.append(info);
		readAble.setCaretPosition(readAble.getText().length());      
	}
	
	public void insertMessage(TaskEvent task){
		String info = task.getSource();
		info = "【" + task.getMaker().getAcount() +"】" + new SimpleDateFormat("HH-mm-ss").format(task.getTime())+ "\r\n" + info +"\r\n"; 
		readAble.append(info);
		readAble.setCaretPosition(readAble.getText().length());      
	}
	
	public void messageArrived(MessageEvent event) {
		Message ms = event.getSource();
		Logger.getLogger(DefaultModelChartController.class).debug("获取消息  ："+event);
		if(ms.getMessageType() == MessageType.CHART ){
			if(((ChartMessage) ms).getAccount().equals(ownner.getAcount())){
				String info = ((ChartMessage) ms).getMes();
				info = "【" + ((ChartMessage) ms).getAccount() +"】" + new SimpleDateFormat("HH-mm-ss").format(new Date())+ "\r\n" + info + "\r\n";
				readAble.append(info);
				readAble.setCaretPosition(readAble.getText().length());
			}
		}
		if(ms.getMessageType() == MessageType.IP_INFO){
			IpInfoMessage mes = (IpInfoMessage) ms;
			this.ownner.setIp(mes.getIpAddr());
			this.ownner.setUserClientPort(mes.getClientListenPort());
		}
		if(ms.getMessageType() == MessageType.USER_NOT_ONLINE){
			String info = "对方不在线，将采用留言方式发送，待对方上线时，发送\r\n";
			readAble.append(info);
			readAble.setCaretPosition(readAble.getText().length());  
		}
		if(ms.getMessageType() == MessageType.LEAVE_WORDS){
			String info = ((TaskEvent) ms).getSource();
			info = "【" + ((TaskEvent) ms).getMaker().getAcount() +"】" + new SimpleDateFormat("HH-mm-ss").format(((TaskEvent) ms).getTime())+ "\r\n" + info + "\r\n";
			readAble.append(info);
			readAble.setCaretPosition(readAble.getText().length());
		}
		if(ms.getMessageType() == MessageType.SUCCESS_UPLOAD){
			JOptionPane.showMessageDialog(this, "成功上传聊天记录");
			return;
		}
		if(ms.getMessageType() == MessageType.DOWNLOAD_CHART_CONTENT){
			DownloadMessage dm = (DownloadMessage) ms;
			if((!dm.getType()) && dm.getObj().equals(ownner.getAcount())){
				DownloadListDialog dld =  new DownloadListDialog();
				dld.setList(dm.getAnswer());
				dld.setVisible(true);
			}
			
		}
	}
}
